package com.jyh.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jyh.common.R;
import com.jyh.pojo.Category;
import com.jyh.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 修改
     * @param category
     * @return
     */
    @PutMapping
    public R<String> updateCategory(@RequestBody Category category){
        log.info("传入的修改:{}",category);
//        LambdaQueryWrapper<Category> lwq=new LambdaQueryWrapper();
//        lwq.eq(Category::getId,category.getId());
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 新增
     * @param category
     * @return
     */
    @PostMapping
    public R<String> addCategory(@RequestBody Category category){
//        log.info("传入的新增:{}",category);
        boolean b = categoryService.save(category);
        return b?R.success("新增成功"):R.error("新增失败");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize){
        //log.info("page:{},pageSize:{}",page,pageSize);

        //按sort升序排序
        LambdaQueryWrapper<Category> lqw=new LambdaQueryWrapper();
        lqw.orderByAsc(Category::getSort);

        //创建分页器
        Page<Category> pageInfo=new Page(page,pageSize);

        categoryService.page(pageInfo,lqw);

        return R.success(pageInfo);
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long ids){
        log.info("id:{}",ids);

        //交给业务层自定义方法判断是否关联菜品和套餐
        categoryService.myDeleteById(ids);

        return R.success("删除成功");
    }



    @GetMapping("/list")
    public R<List<Category>> getList(Category category){
//        log.info("type:{}",type);
        LambdaQueryWrapper<Category> lqw=new LambdaQueryWrapper<>();
        lqw.eq(category.getType()!=null,Category::getType,category.getType()).orderByAsc(Category::getSort);
        List<Category> list = categoryService.list(lqw);
        return R.success(list);
    }
}
